package cn.hzw.supermarket.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import cn.hzw.supermarket.R;
import cn.hzw.supermarket.databinding.ActivityRegisterBinding;
import cn.hzw.supermarket.domain.User;
import cn.hzw.supermarket.model.ResultInfo;
import cn.hzw.supermarket.util.StringUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {
    private ActivityRegisterBinding binding;
    public String username,password,phone,email,gender;
    static User user;
    final OkHttpClient client = new OkHttpClient();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏标题栏以及状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.tvLogin.setOnClickListener(v ->{
            Intent intent = new Intent(this,LoginActivity.class);
            startActivity(intent);
        });
        binding.layoutTitle.ivBack.setOnClickListener(v ->{
            finish();
        });
        binding.layoutTitle.tvTitle.setText("注册");
        binding.tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取相关参数
                username = binding.etUsername.getText().toString().trim();
                password = binding.etPassword.getText().toString().trim();
                phone = binding.etPhone.getText().toString().trim();
                email = binding.etEmail.getText().toString().trim();
                gender = binding.spnSex.getSelectedItem().toString().trim();
                Log.d("TAG", "onClick: "+gender);
                //通过okhttp发起post请求
                if (username.isEmpty()||password.isEmpty()||phone.isEmpty()||email.isEmpty()||gender.isEmpty()){
                    Toast.makeText(RegisterActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                }else if (!StringUtils.isMobilePhone(phone)){
                    Toast.makeText(RegisterActivity.this, "手机号格式错误", Toast.LENGTH_SHORT).show();
                }
                else if (!StringUtils.checkEmail(email)){
                    Toast.makeText(RegisterActivity.this, "邮箱格式错误", Toast.LENGTH_SHORT).show();
                }
//                else if (!StringUtils.isEmail(email)){
//                    Toast.makeText(RegisterActivity.this, "邮箱格式错误", Toast.LENGTH_SHORT).show();
//                }
                else {
                    postRequest(username,password,phone,email,gender);
                }
            }
        });
    }

    /**
     * post 请求后台
     * @param username 用户名
     * @param password 密码
     * @param phone 手机号
     * @param email 邮箱
     * @param gender 性别
     */
    private void postRequest(String username, String password, String phone, String email, String gender) {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        JSONObject userJsonObj = new JSONObject();
        try {
            userJsonObj.put("username",username);
            userJsonObj.put("password",password);
            userJsonObj.put("phone",phone);
            userJsonObj.put("email",email);
            userJsonObj.put("gender",gender);
        }catch (JSONException e){
            e.printStackTrace();
        }
        RequestBody userMessage = RequestBody.create(JSON,""+userJsonObj);
        Log.d("TAG", "postRequest: "+userJsonObj);
        //发起请求
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/user/register")
                .post(userMessage)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e);
                System.out.println("连接失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();//接收从后端传递过来的JSON字符串
                System.out.println(result);
                Log.d("TAG", "onResponse:111 "+result);
                ResultInfo resultInfo = new ResultInfo();
                resultInfo = JSONObject.parseObject(result,ResultInfo.class);//将JSON字符串转换为对象
                System.out.println(resultInfo.isSuccess());
                Log.d("TAG", "onResponse: "+resultInfo.isSuccess());
                if (resultInfo.isSuccess()==false){
                    Looper.prepare();
                    Toast.makeText(RegisterActivity.this,"用户名已存在",Toast.LENGTH_LONG).show();
                    Looper.loop();
                }else if (resultInfo.isSuccess()==true){
                    user = new User();
                    user = resultInfo.getUser();
                    System.out.println(user);
                    finish();
                }
            }
        });
        //设置Intent回调 并设置回调内容
        Intent intent = new Intent();
        intent.putExtra("data",username);
        intent.putExtra("data2",password);
        setResult(2,intent);
    }
}